package com.yyks.es.dubbo.service;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.yeyks.common.base.Arguments;
import com.yyks.es.dubbo.constants.EsIndexConstant;
import com.yyks.es.dubbo.pojo.model.EsHotelInfo;
import com.yyks.es.dubbo.pojo.model.EsRoomCalendarInfo;
import com.yyks.es.dubbo.pojo.model.EsRoomInfo;
import com.yyks.es.dubbo.pojo.model.base.BasalSearchParam;
import com.yyks.es.dubbo.pojo.model.base.EsSort;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Service;
import org.elasticsearch.action.admin.indices.get.GetIndexRequest;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.geo.GeoDistance;
import org.elasticsearch.common.unit.DistanceUnit;
import org.elasticsearch.common.xcontent.ToXContent;
import org.elasticsearch.common.xcontent.XContentHelper;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.*;
import org.elasticsearch.index.reindex.BulkByScrollResponse;
import org.elasticsearch.index.reindex.DeleteByQueryRequest;
import org.elasticsearch.join.query.HasParentQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.GeoDistanceSortBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author shuai
 * @date 2019/10/08 15:44
 */
@Service
@Slf4j
public class ElasticSearchServiceImpl implements ElasticSearchService {

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    /**
     * 创建索引
     *
     * @param indexName 索引名称
     */
    @Override
    public IndexResponse createIndex(String indexName) {
        //首先判断该索引是否存在
        Arguments.isTrue(isExistIndex(indexName), "该索引已存在");
        IndexResponse indexResponse = null;
        try {
            indexResponse = restHighLevelClient.index(new IndexRequest(indexName, EsIndexConstant.NORMAL_TYPE).source(new HashMap()), RequestOptions.DEFAULT);
            long version = indexResponse.getVersion();
            log.info("create index successfully! " + version);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return indexResponse;
    }

    /**
     * 创建文档
     *
     * @param map       文档集合（必须包含id）
     * @param indexName 索引名称
     */
    @Override
    public IndexResponse createDocument(Map<String, Object> map, String indexName, String idColumnName) {
        IndexResponse indexResponse = null;
        try {
            indexResponse = restHighLevelClient.index(new IndexRequest(indexName, EsIndexConstant.NORMAL_TYPE, (String) map.get(idColumnName)).source(map), RequestOptions.DEFAULT);
            long version = indexResponse.getVersion();
            log.info("create document successfully! " + version);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return indexResponse;
    }


    /**
     * 创建文档
     *
     * @param json      文档集合（必须包含id）
     * @param indexName 索引名称
     */
    @Override
    public IndexResponse createDocument(String json, String indexName, String id) {
        IndexResponse indexResponse = null;
        try {
            IndexRequest request = new IndexRequest(indexName, EsIndexConstant.NORMAL_TYPE, id);
            request.source(json, XContentType.JSON).routing("hotel");
            indexResponse = restHighLevelClient.index(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return indexResponse;
    }

    /**
     * 批量创建酒店文档数据
     *
     * @param esHotelInfoList 酒店集合
     * @param indexName       索引名称
     * @return 返回结果
     */
    @Override
    public BulkResponse createMoreDocument(List<EsHotelInfo> esHotelInfoList, String indexName) {
        BulkRequest bulkAddRequest = new BulkRequest();
        BulkResponse bulkResponse = null;
        try {
            for (EsHotelInfo esHotelInfo : esHotelInfoList) {
                IndexRequest indexRequest = new IndexRequest(indexName, EsIndexConstant.NORMAL_TYPE, String.valueOf(esHotelInfo.getId()));
                indexRequest.source(JSONUtil.toJsonStr(esHotelInfo), XContentType.JSON);
                bulkAddRequest.add(indexRequest);
            }
            bulkResponse = restHighLevelClient.bulk(bulkAddRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return bulkResponse;
    }

    @Override
    public IndexResponse createHotelDocument(String json, String indexName, String id) {
        IndexResponse indexResponse = null;
        String indexNameType = EsIndexConstant.NORMAL_TYPE;
        try {

            IndexRequest request = new IndexRequest(indexName, indexNameType, id);
            request.source(json, XContentType.JSON).routing(EsIndexConstant.ROUTING_HOTEL);
            indexResponse = restHighLevelClient.index(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return indexResponse;
    }

    /**
     * 批量创建酒店文档数据
     *
     * @param esHotelInfoList 酒店集合
     * @param indexName       索引名称
     * @return 返回结果
     */
    @Override
    public BulkResponse createMoreHotelDocument(List<EsHotelInfo> esHotelInfoList, String indexName) {
        BulkRequest bulkAddRequest = new BulkRequest();
        BulkResponse bulkResponse = null;
        String indexNameType = EsIndexConstant.NORMAL_TYPE;
        try {
            for (EsHotelInfo esHotelInfo : esHotelInfoList) {
                IndexRequest indexRequest = new IndexRequest(indexName, indexNameType, esHotelInfo.getHotelId());
                indexRequest.source(JSONUtil.toJsonStr(esHotelInfo), XContentType.JSON)
                        .routing(EsIndexConstant.ROUTING_HOTEL);
                bulkAddRequest.add(indexRequest);
            }
            bulkResponse = restHighLevelClient.bulk(bulkAddRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return bulkResponse;
    }

    /**
     * 批量创建房间文档数据
     *
     * @param roomInfoList 房间集合
     * @param indexName    索引名称
     * @return 返回结果
     */
    @Override
    public BulkResponse createMoreRoomDocument(List<EsRoomInfo> roomInfoList, String indexName) {
        BulkRequest bulkAddRequest = new BulkRequest();
        BulkResponse bulkResponse = null;
        String indexNameType = EsIndexConstant.NORMAL_TYPE;
        try {
            if (!CollectionUtils.isEmpty(roomInfoList)) {
                for (EsRoomInfo roomInfo : roomInfoList) {
                    IndexRequest indexRequest = new IndexRequest(indexName, indexNameType, roomInfo.getRoomId());
                    indexRequest.source(JSONUtil.toJsonStr(roomInfo), XContentType.JSON)
                            .routing(EsIndexConstant.ROUTING_HOTEL);
                    bulkAddRequest.add(indexRequest);
                }
                bulkResponse = restHighLevelClient.bulk(bulkAddRequest, RequestOptions.DEFAULT);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bulkResponse;
    }

    /**
     * 批量创建房态文档数据
     *
     * @param roomCalendarInfoList 房间集合
     * @param indexName            索引名称
     * @return 返回结果
     */
    @Override
    public BulkResponse createMoreRoomCalendarDocument(List<EsRoomCalendarInfo> roomCalendarInfoList, String indexName) {
        BulkRequest bulkAddRequest = new BulkRequest();
        BulkResponse bulkResponse = null;
        String indexNameType = EsIndexConstant.NORMAL_TYPE;
        try {
            if (!CollectionUtils.isEmpty(roomCalendarInfoList)) {
                for (EsRoomCalendarInfo roomCalendarInfo : roomCalendarInfoList) {
                    IndexRequest indexRequest = new IndexRequest(indexName, indexNameType, roomCalendarInfo.getCalendarId());
                    indexRequest.source(JSON.toJSONString(roomCalendarInfo), XContentType.JSON)
                            .routing(EsIndexConstant.ROUTING_HOTEL);
                    bulkAddRequest.add(indexRequest);
                }
                bulkResponse = restHighLevelClient.bulk(bulkAddRequest, RequestOptions.DEFAULT);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bulkResponse;
    }

    @Override
    public BulkResponse updateMoreRoomCalendar(List<EsRoomCalendarInfo> roomCalendarInfoList, String indexName){

        BulkRequest bulkAddRequest = new BulkRequest();
        BulkResponse bulkResponse = null;
        String indexNameType = EsIndexConstant.NORMAL_TYPE;
        try {
            if (!CollectionUtils.isEmpty(roomCalendarInfoList)) {
                Map<String, Integer> priceMap;
                for (EsRoomCalendarInfo roomCalendarInfo : roomCalendarInfoList) {
                    priceMap = Maps.newHashMap();
                    UpdateRequest updateRequest = new UpdateRequest(indexName, indexNameType, roomCalendarInfo.getCalendarId());
                    priceMap.put("salePrice", roomCalendarInfo.getSalePrice());
                    priceMap.put("bottomPrice", roomCalendarInfo.getBottomPrice());
                    updateRequest.doc(priceMap).routing(EsIndexConstant.ROUTING_HOTEL);
                    bulkAddRequest.add(updateRequest);
                }
                bulkResponse = restHighLevelClient.bulk(bulkAddRequest, RequestOptions.DEFAULT);
            }
        }catch (IOException e){
            e.printStackTrace();
        }
        return bulkResponse;
    }

    /**
     * 更新文档
     *
     * @param map       文档集合（必须包含id）
     * @param indexName 索引名称
     */
    @Override
    public UpdateResponse updateDocument(Map<String, Object> map, String indexName, String idColumnName) {
        UpdateResponse updateResponse = null;
        try {
            updateResponse = restHighLevelClient.update(new UpdateRequest(indexName, EsIndexConstant.NORMAL_TYPE, (String) map.get(idColumnName)).doc(map), RequestOptions.DEFAULT);
            log.info("create document successfully! " + updateResponse.getVersion());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return updateResponse;
    }

    /**
     * 删除文档
     *
     * @param indexName 索引名称
     * @param id        文档id
     */
    @Override
    public DeleteResponse deleteDocument(String indexName, String id) {
        DeleteResponse deleteResponse = null;
        try {
            DeleteRequest request = new DeleteRequest(indexName, EsIndexConstant.NORMAL_TYPE, id);
            deleteResponse = restHighLevelClient.delete(request, RequestOptions.DEFAULT);
            log.info("Delete document successfully! \n" + deleteResponse.toString() + "\n" + deleteResponse.status());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return deleteResponse;
    }

    /**
     * 底层基础搜索
     *
     * @param queryBuilder 查询条件
     * @param param        公共条件
     * @param indexs       索引名称
     */
    @Override
    public SearchResponse search(QueryBuilder queryBuilder, BasalSearchParam param, String... indexs) {
        try {
            SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
            searchSourceBuilder.query(queryBuilder);
            searchSourceBuilder.from((param.getPageNo() - 1) * param.getPageSize());
            searchSourceBuilder.size(param.getPageSize());
            List<EsSort> esSorts = param.getEsSorts();
            if (null != esSorts) {
                esSorts.forEach(order -> searchSourceBuilder.sort(order.getProperty(), order.getDirection()));
            }
            if (null != param.getPositionX() && null != param.getPositionY()) {
                GeoDistanceSortBuilder sortBuilder = SortBuilders.geoDistanceSort("location", param.getPositionY(), param.getPositionX())
                        .geoDistance(GeoDistance.ARC)
                        .unit(DistanceUnit.METERS)
                        .order(SortOrder.ASC);
                searchSourceBuilder.sort(sortBuilder);
            }
            SearchRequest searchRequest = new SearchRequest(indexs);
            searchRequest.types(EsIndexConstant.NORMAL_TYPE);
            searchRequest.source(searchSourceBuilder);
            try {
                log.info("es查询语句------{}", XContentHelper.toXContent(searchRequest.source(), XContentType.JSON, ToXContent.EMPTY_PARAMS, false).toBytesRef().utf8ToString());
            } catch (Exception e) {
                e.printStackTrace();
            }
            return restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 默认CN
     *
     * @param sourceType 资源类型
     * @param calendarId 房态ID
     * @return
     */
    @Override
    public List<EsRoomCalendarInfo> c2bSearchCalendar(String indexName, String sourceType, String calendarId, Integer pageSize,
                                                      Integer pageNo) {

        List<EsRoomCalendarInfo> esRoomCalendarInfoList = Lists.newArrayList();
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        if (StringUtils.isEmpty(calendarId)) {
            calendarId = EsIndexConstant.ID_PREX_CNBOOKING_CALENDAR;
        }
        QueryBuilder builder = QueryBuilders.prefixQuery("calendarId", calendarId);
        /*BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        boolQueryBuilder.must(QueryBuilders.termQuery("sourceType", sourceType));*/
        searchSourceBuilder.query(builder);
        searchSourceBuilder.from((pageNo - 1) * pageSize);
        searchSourceBuilder.size(pageSize);

        SearchRequest searchRequest = new SearchRequest(indexName);
        searchRequest.types(EsIndexConstant.NORMAL_TYPE);
        searchRequest.source(searchSourceBuilder);
        try {
            SearchResponse search = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
            if (null == search) {
                return null;
            }
            SearchHits hits = search.getHits();
            SearchHit[] searchHits = hits.getHits();
            for (SearchHit searchHit : searchHits) {
                String sourceAsString = searchHit.getSourceAsString();
                if (StrUtil.isNotBlank(sourceAsString)) {
                    EsRoomCalendarInfo esRoomCalendarInfo = JSON.parseObject(sourceAsString, EsRoomCalendarInfo.class);
                    if (null != esRoomCalendarInfo) {
                        esRoomCalendarInfoList.add(esRoomCalendarInfo);
                    }
                }
            }
            return esRoomCalendarInfoList;
        } catch (IOException e) {
            log.info("查询房态信息异常");
            e.printStackTrace();
        }

        return null;
    }

    @Override
    public List<EsRoomInfo> esRoomSearch(String indexName, String sourceType, String roomId, Integer pageSize, Integer pageNo) {

        List<EsRoomInfo> roomInfoList = Lists.newArrayList();
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        if (StringUtils.isEmpty(roomId)) {
            roomId = EsIndexConstant.ID_PREX_CNBOOKING_ROOM;
        }
        QueryBuilder builder = QueryBuilders.prefixQuery("roomId", roomId);
        searchSourceBuilder.query(builder);
        searchSourceBuilder.from((pageNo - 1) * pageSize);
        searchSourceBuilder.size(pageSize);
        SearchRequest searchRequest = new SearchRequest(indexName);
        searchRequest.types(EsIndexConstant.NORMAL_TYPE);
        searchRequest.source(searchSourceBuilder);
        try {
            SearchResponse search = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
            if (null == search) {
                return null;
            }
            SearchHits hits = search.getHits();
            SearchHit[] searchHits = hits.getHits();
            for (SearchHit searchHit : searchHits) {
                String sourceAsString = searchHit.getSourceAsString();
                if (StrUtil.isNotBlank(sourceAsString)) {
                    EsRoomInfo esRoomInfo = JSON.parseObject(sourceAsString, EsRoomInfo.class);
                    if (null != esRoomInfo) {
                        roomInfoList.add(esRoomInfo);
                    }
                }
            }
            return roomInfoList;
        } catch (IOException e) {
            log.info("查询房间信息异常");
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 根据条件查询酒店信息
     *
     * @param indexName  索引名称
     * @param sourceType 资源类型
     * @param pageSize   也大小
     * @param pageNo     当前页
     * @return
     */
    @Override
    public List<EsHotelInfo> esHotelSearch(String indexName, String sourceType, String hotelId, Integer pageSize, Integer pageNo) {

        List<EsHotelInfo> hotelInfoList = Lists.newArrayList();
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        if (StringUtils.isEmpty(hotelId)) {
            hotelId = EsIndexConstant.ID_PREX_CNBOOKING_HOTEL;
        }
        QueryBuilder builder = QueryBuilders.prefixQuery("hotelId", hotelId);
        searchSourceBuilder.query(builder);
        searchSourceBuilder.from((pageNo - 1) * pageSize);
        searchSourceBuilder.size(pageSize);
        SearchRequest searchRequest = new SearchRequest(indexName);
        searchRequest.types(EsIndexConstant.NORMAL_TYPE);
        searchRequest.source(searchSourceBuilder);
        try {
            SearchResponse search = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
            if (null == search) {
                return null;
            }
            SearchHits hits = search.getHits();
            SearchHit[] searchHits = hits.getHits();
            for (SearchHit searchHit : searchHits) {
                String sourceAsString = searchHit.getSourceAsString();
                if (StrUtil.isNotBlank(sourceAsString)) {
                    EsHotelInfo esHotelInfo = JSON.parseObject(sourceAsString, EsHotelInfo.class);
                    if (null != esHotelInfo) {
                        hotelInfoList.add(esHotelInfo);
                    }
                }
            }
            return hotelInfoList;
        } catch (IOException e) {
            log.info("查询房间信息异常");
            e.printStackTrace();
        }
        return null;

    }

    /**
     * 更新图片
     *
     * @param id        主键ID （【酒店/房间】前缀+id）
     * @param map       更新对象Map
     * @param indexName 索引名称
     * @return 返回更新结果
     */
    @Override
    public UpdateResponse updateHotelOrRoomImage(String id, Map<String, String> map, String indexName) {

        UpdateResponse updateResponse = null;

        try {
            UpdateRequest updateRequest = new UpdateRequest(EsIndexConstant.INDEX_HOTEL2, EsIndexConstant.NORMAL_TYPE,
                    id);
            updateRequest.doc(map).routing(EsIndexConstant.ROUTING_HOTEL);

            updateResponse = restHighLevelClient.update(updateRequest, RequestOptions.DEFAULT);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return updateResponse;
    }

    /**
     * 删除过期的房态信息
     *
     * @param indexName 索引名称
     * @param indexIds  主键唯一ID集合
     * @return
     */
    @Override
    public BulkResponse deleteOverTimeCalendar(String indexName, List<String> indexIds) {

        BulkRequest bulkRequest = new BulkRequest();
        BulkResponse deleteResponse = null;
        try {
            if (!CollectionUtils.isEmpty(indexIds)) {
                for (String id : indexIds) {
                    DeleteRequest deleteRequest = new DeleteRequest(EsIndexConstant.INDEX_HOTEL2, EsIndexConstant.NORMAL_TYPE,
                            id);
                    deleteRequest.routing(EsIndexConstant.ROUTING_HOTEL);
                    bulkRequest.add(deleteRequest);
                }
                deleteResponse = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return deleteResponse;
    }

    /**
     * 判断索引是否已经存在
     *
     * @param indexName
     * @return
     */
    private boolean isExistIndex(String indexName) {
        GetIndexRequest getIndexRequest = new GetIndexRequest();
        getIndexRequest.indices(indexName);
        getIndexRequest.local(false);
        getIndexRequest.humanReadable(true);
        boolean flag = false;
        try {
            flag = restHighLevelClient.indices().exists(getIndexRequest, RequestOptions.DEFAULT);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return flag;
    }

    /**
     * 根据父类ID 查询子类集合， 如果为空，则需要清空该酒店
     * @param hotelSourceId 酒店ID
     * @return 返回客房列表
     */
    @Override
    public List<EsRoomInfo> queryByParentId(String hotelSourceId, String indexName){

        List<EsRoomInfo> roomInfoList = Lists.newArrayList();
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();

        InnerHitBuilder innerHitBuilder = new InnerHitBuilder().setSize(100);

        HasParentQueryBuilder parentQueryBuilder = new HasParentQueryBuilder(EsIndexConstant.JOIN_TYPE_HOTEL,
                new MatchQueryBuilder("sourceId",hotelSourceId), false);
        parentQueryBuilder.innerHit(innerHitBuilder);
        searchSourceBuilder.query(parentQueryBuilder);
        searchSourceBuilder.from(0);
        searchSourceBuilder.size(5000);
        SearchRequest searchRequest = new SearchRequest(indexName);
        searchRequest.types(EsIndexConstant.NORMAL_TYPE);
        searchRequest.source(searchSourceBuilder);
        try {
            SearchResponse search = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
            if (null == search) {
                return null;
            }
            SearchHits hits = search.getHits();
            SearchHit[] searchHits = hits.getHits();
            for (SearchHit searchHit : searchHits) {
                String sourceAsString = searchHit.getSourceAsString();
                if (StrUtil.isNotBlank(sourceAsString)) {
                    EsRoomInfo esRoomInfo = JSON.parseObject(sourceAsString, EsRoomInfo.class);
                    if (null != esRoomInfo) {
                        roomInfoList.add(esRoomInfo);
                    }
                }
            }
            return roomInfoList;
        } catch (IOException e) {
            log.info("查询房间信息异常");
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public List<EsRoomCalendarInfo> queryCalendarByParentId(String roomSourceId, String indexName) {

        List<EsRoomCalendarInfo> esRoomCalendarInfoList = Lists.newArrayList();
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();

        InnerHitBuilder innerHitBuilder = new InnerHitBuilder().setSize(100);

        HasParentQueryBuilder parentQueryBuilder = new HasParentQueryBuilder(EsIndexConstant.JOIN_TYPE_ROOM,
                new MatchQueryBuilder("sourceId",roomSourceId), false);
        parentQueryBuilder.innerHit(innerHitBuilder);
        searchSourceBuilder.query(parentQueryBuilder);
        searchSourceBuilder.from(0);
        searchSourceBuilder.size(2000);

        SearchRequest searchRequest = new SearchRequest(indexName);
        searchRequest.types(EsIndexConstant.NORMAL_TYPE);
        searchRequest.source(searchSourceBuilder);
        try {
            SearchResponse search = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
            if (null == search) {
                return null;
            }
            SearchHits hits = search.getHits();
            SearchHit[] searchHits = hits.getHits();
            for (SearchHit searchHit : searchHits) {
                String sourceAsString = searchHit.getSourceAsString();
                if (StrUtil.isNotBlank(sourceAsString)) {
                    EsRoomCalendarInfo esRoomCalendarInfo = JSON.parseObject(sourceAsString, EsRoomCalendarInfo.class);
                    if (null != esRoomCalendarInfo) {
                        esRoomCalendarInfoList.add(esRoomCalendarInfo);
                    }
                }
            }
            return esRoomCalendarInfoList;
        } catch (IOException e) {
            log.info("查询房态信息异常");
            e.printStackTrace();
        }

        return null;
    }

    @Override
    public BulkByScrollResponse deleteCalendarByHotelId(String hotelId, String indexName) {
        DeleteByQueryRequest deleteByQueryRequest = new DeleteByQueryRequest(indexName);
        BoolQueryBuilder builder = new BoolQueryBuilder();
        builder.must(QueryBuilders.prefixQuery("calendarId", EsIndexConstant.ID_PREX_CNBOOKING_CALENDAR));
        builder.must(QueryBuilders.termQuery("hotelId", hotelId));
        builder.must(QueryBuilders.termQuery("sourceType", "cn"));
        deleteByQueryRequest.setQuery(builder);
        deleteByQueryRequest.setConflicts("proceed");
        deleteByQueryRequest.setBatchSize(5000);
        //并行
        deleteByQueryRequest.setSlices(2);
        //路由信息
        deleteByQueryRequest.setRouting("hotel");


        //刷新索引
        deleteByQueryRequest.setRefresh(true);
        try {
            //删除信息
            return restHighLevelClient.deleteByQuery(deleteByQueryRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     *
     * @param hotelId
     * @param roomId
     *
     * @param indexName
     * @return
     */
    @Override
    public BulkByScrollResponse deleteCalendarByHotelAndRoomId(String hotelId, String roomId, String indexName) {
        DeleteByQueryRequest deleteByQueryRequest = new DeleteByQueryRequest(indexName);
        BoolQueryBuilder builder = new BoolQueryBuilder();
        builder.must(QueryBuilders.prefixQuery("calendarId", EsIndexConstant.ID_PREX_CNBOOKING_CALENDAR));
        builder.must(QueryBuilders.termQuery("hotelId", hotelId));
        builder.must(QueryBuilders.termQuery("roomId", roomId));
        builder.must(QueryBuilders.termQuery("sourceType", "cn"));
        deleteByQueryRequest.setQuery(builder);
        deleteByQueryRequest.setConflicts("proceed");
        deleteByQueryRequest.setBatchSize(5000);
        //并行
        deleteByQueryRequest.setSlices(2);
        //路由信息
        deleteByQueryRequest.setRouting("hotel");

        //刷新索引
        deleteByQueryRequest.setRefresh(true);
        try {
            //删除信息
            return restHighLevelClient.deleteByQuery(deleteByQueryRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
